package com.zaofan.service;

import com.zaofan.bean.Account;
import com.zaofan.bean.AccountLog;
import com.zaofan.bean.OpenBuilder;
import com.zaofan.bean.SmsLog;
import com.zaofan.cache.CacheManage;
import com.zaofan.constant.TypeConstant;
import com.zaofan.dao.AccountDao;
import com.zaofan.dao.OpenBuilderDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.mobile.bean.Fans;
import com.zaofan.mobile.bean.HotelInfo;
import com.zaofan.utils.SendSms;
import com.zaofan.utils.WebUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

public class AccountService {

	private AccountDao accountDao = new AccountDao();
	private SmsLogService smsLogService = new SmsLogService();
	private AccountLogService accountLogService = new AccountLogService();
	private HotelService hotelService = new HotelService();
	private OpenBuilderDao openBuilderDao = new OpenBuilderDao();

	public void delete(Account account) {
		accountDao.del(account);
	}

	public void add(Account account) {
		accountDao.add(account);
	}

	public void update(Account account) throws ServiceException {
		if (WebUtils.isEmpty(account.getId())) {
			throw new ServiceException("请填写正确的用户id!!");
		}
		Account target = this.findById(account.getId());
		if (target == null) {
			throw new ServiceException("请填写正确的用户id!!");
		}
		accountDao.update(account);
	}

	public void updateAccountInfo(Account account) throws ServiceException {
		if (WebUtils.isEmpty(account.getId())) {
			throw new ServiceException("请填写正确的用户id!!");
		}
		Account target = this.findById(account.getId());
		if (target == null) {
			throw new ServiceException("请填写正确的用户id!!");
		}
		if (!WebUtils.isEmpty(account.getNickname())) {

			target.setNickname(account.getNickname());
		}
		if (!WebUtils.isEmpty(account.getSex())) {

			target.setSex(account.getSex());
		}
		if (!WebUtils.isEmpty(account.getBirthday())) {

			target.setBirthday(account.getBirthday());
		}
		accountDao.update(target);
	}

	public List<Account> findAll(Map<String, Object> params) {
		List<Account> data = accountDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return accountDao.count(params);
	}

	public Account findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return accountDao.findOne(params);
	}

	public Account login(Account account) throws ServiceException {
		if (WebUtils.isEmpty(account)) {
			throw new ServiceException("请填写正确的信息!!");
		}
		if (WebUtils.isEmpty(account.getMobile())) {
			throw new ServiceException("请填写正确的手机号码!!");
		}
		if (WebUtils.isEmpty(account.getPassword())) {
			throw new ServiceException("请填写正确的登录密码!!");
		}
		Account acc = findByMobile(account.getMobile());
		if (acc == null) {
			throw new ServiceException("对不起,不存在此用户!!");
		}
		if (!acc.getPassword().equals(WebUtils.MD5(account.getPassword()))) {
			throw new ServiceException("对不起,请填写正确的密码!!");
		}
		if ("y".equals(acc.getFreeze())) {
			throw new ServiceException("对不起,由于一些原因,您的账号暂时被禁用了,如有疑问,可以联系我们的客服!!");
		}
		acc.setLastLoginTime(new Date());
		acc.setPlatform(account.getPlatform());
		if (account.getDeviceId() != null && !"".equals(account.getDeviceId())) {
			if (!account.getDeviceId().equals(acc.getDeviceId())) {
				// 用户 更换手机登录 旧设备需 清除 登录
				// 更新不同账号切换
				Account a = findByDeviceId(account.getDeviceId());
				if (a != null) {
					a.setDeviceId("");
					update(a);
				}
			}
		}
		acc.setDeviceId(account.getDeviceId());
		acc.setAppVersion(account.getAppVersion());
		accountDao.update(acc);
		return acc;
	}

	private Account findByDeviceId(String deviceId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("deviceId", deviceId);
		return accountDao.findOne(params);
	}

	public Account findByMobile(String mobile) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", mobile);
		return accountDao.findOne(params);
	}

	public void sendRegisterCode(String mobile, String code) throws ServiceException {
		if (WebUtils.isEmpty(mobile)) {
			throw new ServiceException("请填写正确的手机号码!!");
		}
		if (!WebUtils.isMobileNO(mobile)) {
			throw new ServiceException("手机号码格式不正确!!");
		}
		Account acc = findByMobile(mobile);
		if (acc != null) {
			throw new ServiceException("对不起,您的号码已经被注册了!!");
		}
		Long count = smsLogService.CountTodayLogs(mobile);
		if (count > 3) {
			throw new ServiceException("对不起,您的号码发送多次,请明天再试吧!!");
		}
		int result = SendSms.sendRegisterCode(mobile, code);
		if (result == 2) {
			SmsLog log = new SmsLog();
			log.setCode(code);
			log.setMobile(mobile);
			log.setSendTime(new Date());
			log.setType(TypeConstant.SEND_SMS_TYPE_REGISTER);
			smsLogService.add(log);
		} else {
			throw new ServiceException("对不起,您的号码有误,请稍后再试!!");
		}
	}

	public Account register(Account account) throws ServiceException {
		if (!WebUtils.isMobileNO(account.getMobile())) {
			throw new ServiceException("请填写正确的手机号码!!");
		}
		Account acc = findByMobile(account.getMobile());
		if (acc != null) {
			throw new ServiceException("对不起,您的号码已经被注册了!!");
		}
		account.setFreeze("n");
		account.setLastLoginTime(new Date());
		account.setRegeistDate(new Date());
		account.setEmailIsActive("y");
		account.setMoney(new BigDecimal(0));
		if (CacheManage.setting.getRegisterReturn() == 1) {
			if(account.getCityId()!=1)
			{
				account.setMoney(CacheManage.setting.getRegisterReturnMoney());
			}
			else {
				account.setMoney(new BigDecimal(0));
			}

		}
		account.setNickname(account.getMobile());
		account.setRank("R1");
		account.setPhoto("");
		account.setPassword(WebUtils.MD5(account.getPassword()));
		account.setNickname(account.getMobile());
		
		//邀请码解码成手机
		String referee = account.getReferee();
		System.err.println("referee:" + referee);
		if (referee != null && !"".equals(referee.trim())) {
			//如果是不是手机账号
			if (!WebUtils.isMobileNO(referee.trim())) {
				 String temp = new StringBuffer(referee.trim()).reverse().toString();
			     Long refereeUserId = Long.valueOf(temp) - 1L;
			     Account refereeUser = findById(refereeUserId.intValue());
			     if (refereeUser == null) {
			    	 throw new ServiceException("对不起,没有找到邀请码: " + referee + " 对应的用户");
			     }
			     account.setReferee(refereeUser.getMobile().trim());
			}
			//如果是手机账号
			/*else {
				Account refereeUser = findByMobile(referee.trim());
				if (refereeUser == null) {
					 throw new ServiceException("对不起,没有找到邀请码: " + referee + " 对应的用户");
				}
				account.setReferee(refereeUser.getMobile().trim());
			}*/
		}
		
		accountDao.add(account);
		Account user = findByMobile(account.getMobile());
		if (CacheManage.setting.getRegisterReturn() == 1) {
			AccountLog log = new AccountLog();
			log.setAccountId(user.getId());
			log.setAccountMobile(user.getMobile());
			log.setAddTime(new Date());
			log.setMoney(account.getMoney());
			log.setBeforeMoney(new BigDecimal(0));
			log.setAfterMoney(CacheManage.setting.getRegisterReturnMoney());
			log.setType(TypeConstant.log_type_register_return);
			accountLogService.add(log);
		}
		return user;
	}

	public void sendFindCode(String mobile, String code) throws ServiceException {
		if (!WebUtils.isMobileNO(mobile)) {
			throw new ServiceException("请填写正确的手机号码!!");
		}
		Account acc = findByMobile(mobile);
		if (acc == null) {
			throw new ServiceException("对不起,该号码暂未注册!!");
		}
		Long count = smsLogService.CountTodayLogs(mobile);
		if (count > 3) {
			throw new ServiceException("对不起,您的号码发送多次,请明天再试吧!!");
		}
		int result = SendSms.sendFindCode(mobile, code);
		if (result == 2) {
			SmsLog log = new SmsLog();
			log.setCode(code);
			log.setMobile(mobile);
			log.setSendTime(new Date());
			log.setType(TypeConstant.SEND_SMS_TYPE_REGISTER);
			smsLogService.add(log);
		} else {
			throw new ServiceException("对不起,您的号码有误,请售后再试!!");
		}

	}

	public void resetPass(Account account) throws ServiceException {
//		if (!WebUtils.isMobileNO(account.getMobile())) {
//			throw new ServiceException("请填写正确的手机号码!!");
//		}
		Account acc = findByMobile(account.getMobile());
		if (acc == null) {
			throw new ServiceException("对不起,该号码暂未注册!!");
		}
		if (WebUtils.isEmpty(account.getPassword())) {
			throw new ServiceException("请填写正确的新密码!!");
		}
		acc.setPassword(WebUtils.MD5(account.getPassword()));
		accountDao.update(acc);
	}

	public void modifyPass(String id, String old, String password) throws ServiceException {
		if (WebUtils.isEmpty(id)) {
			throw new ServiceException("请填写正确的用户id!!");
		}
		try {
			Integer.valueOf(id);
		} catch (Exception e) {
			throw new ServiceException("请填写正确的用户id!!");
		}
		if (WebUtils.isEmpty(old)) {
			throw new ServiceException("请填写正确的旧密码!!");
		}
		if (WebUtils.isEmpty(password)) {
			throw new ServiceException("请填写正确的新密码!!");
		}
		Account acc = findById(Integer.valueOf(id));
		if (acc == null) {
			throw new ServiceException("对不起,用户信息出错!!");
		}
		if (!acc.getPassword().equals(WebUtils.MD5(old))) {
			throw new ServiceException("对不起,旧密码输入有误!!");
		}
		acc.setPassword(WebUtils.MD5(password));
		accountDao.update(acc);
	}

	public Fans getUserFansInfo(int userId) {
		return accountDao.getUserFansInfo(userId);
	}

	public com.zaofan.mobile.bean.Account findAccountInfo(int id) {
		return accountDao.findAccountInfo(id);
	}

	public void quicklyRegister(String openid, String no, HttpServletResponse response) throws IOException {
		HotelInfo hotelInfo =  hotelService.findOpenHotelByHotelNo(no);

		OpenBuilder openBuilder = openBuilderDao.findByAddressId(hotelInfo.getAddressId());

		if (openBuilder==null){

		}else {
			//根据这些信息快速注册
			Account account = new Account();
			account.setMobile(openid);
			account.setMoney(new BigDecimal(0));
			account.setBuilderId(hotelInfo.getAddressId());
			account.setBuilderName(openBuilder.getBuilderName());
			account.setCityId(openBuilder.getCityId());
			account.setCityName(openBuilder.getCityName());
			account.setDeviceId(openid);
			account.setLastLoginTime(new Date());
			account.setNickname("游客");
			account.setOpenId(openid);
//		由于登录有MD5验证 所以这个密码  无论如何都不会被登对
			account.setPassword(openid);
			account.setPlatform("wechat");
			account.setRegeistDate(new Date());
			accountDao.add(account);
		}
	}

	public void sendQuickMobileCode(String mobile, String code) throws ServiceException {
		if (!WebUtils.isMobileNO(mobile)) {
			throw new ServiceException("请填写正确的手机号码!!");
		}

		Long count = smsLogService.CountTodayLogs(mobile);
		if (count > 3) {
			throw new ServiceException("对不起,您的号码发送多次,请明天再试吧!!");
		}
		int result = SendSms.sendQuickCode(mobile, code);
		if (result == 2) {
			SmsLog log = new SmsLog();
			log.setCode(code);
			log.setMobile(mobile);
			log.setSendTime(new Date());
			log.setType(TypeConstant.SEND_SMS_TYPE_QUICK_MOBILE);
			smsLogService.add(log);
		} else {
			throw new ServiceException("对不起,您的号码有误,请售后再试!!");
		}

	}

	/**
	 * 验证码快速登录
	 * @param account
	 * @return
	 * @throws ServiceException
     */
	public Account                                                                                                                                                                                     quickCodeLogin(Account account) throws ServiceException {
		if (WebUtils.isEmpty(account.getMobile())) {
			throw new ServiceException("请填写正确的手机号码!!");
		}
		Account acc = findByMobile(account.getMobile());
		if (acc == null) {
			acc = quickCodeRegister(account);
		}
		acc.setLastLoginTime(new Date());
		acc.setPlatform(account.getPlatform());
		if (account.getDeviceId() != null && !"".equals(account.getDeviceId())) {
			if (!account.getDeviceId().equals(acc.getDeviceId())) {
				Account a = findByDeviceId(account.getDeviceId());
				if (a != null) {
					a.setDeviceId("");
					update(a);
				}
			}
		}
		acc.setDeviceId(account.getDeviceId());
		acc.setAppVersion(account.getAppVersion());
		accountDao.update(acc);
		return acc;
	}

	/**
	 * 验证码快速注册
	 * @param account
	 * @return
     */
	private Account quickCodeRegister(Account account) {
		//根据这些信息快速注册
		Account acc = new Account();
		acc.setMobile(account.getMobile());
		acc.setMoney(new BigDecimal(0));
		acc.setCityId(account.getCityId());
		acc.setCityName(account.getCityName());
		acc.setDeviceId(account.getDeviceId());
		acc.setLastLoginTime(new Date());
		acc.setNickname("游客");
//		由于登录有MD5验证 所以这个密码  无论如何都不会被登对
		acc.setPassword(account.getMobile());
		acc.setPlatform(account.getPlatform());
		acc.setRegeistDate(new Date());
		accountDao.add(acc);
		return findByMobile(account.getMobile());
	}
}
